package st.lib.base.ui.menu.cascade;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;

import java.util.List;

import st.lib.base.ui.R;
import st.lib.base.ui.gallery.util.OsUtil;

/**
 * @author zhangyu
 * @date 2018/2/12
 */

public class CascadeView extends LinearLayout {

    private OnItemClickListener mClickListener;

    public CascadeView(Context context) {
        super(context);
    }

    public CascadeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CascadeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setData(List<MenuBean> list, OnItemClickListener clickListener) {
        mClickListener = clickListener;
        removeAllViews();
        showChild(list, 0);
    }

    private void showChild(List<MenuBean> list, final int index) {
        ListView listView = (ListView) getChildAt(index);
        if (listView == null) {
            listView = new ListView(getContext());
            LayoutParams params = new
                    LayoutParams(OsUtil.getScreenWidth()/5,
                    OsUtil.getScreenWidth()/4);
            addView(listView, params);
        } else {
            int childCount = getChildCount();
            for (int i = index + 1; i < childCount; i++) {
                View viewNext = getChildAt(i);
                if (viewNext != null) {
                    removeView(viewNext);
                }
            }
        }
        final ArrayAdapter<MenuBean> adapter
                = new ArrayAdapter<>(getContext(), R.layout.item_text_black, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               MenuBean menuBean = adapter.getItem(position);
                if (menuBean != null) {
                    List<MenuBean> children = menuBean.getListChild();
                    if (children != null && !children.isEmpty()) {
                        showChild(children, index + 1);
                    } else {
                        int count = getChildCount();
                        removeViews(1, count - 1);
                        if (mClickListener != null) {
                            mClickListener.onClick(menuBean);
                        }
                    }
                }
            }
        });
    }

    public interface OnItemClickListener {
        void onClick(MenuBean menuBean);
    }
}
